/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.ufc.stopwatchplugin.panel;

import java.awt.event.MouseAdapter;
import java.util.Calendar;
import java.util.Timer;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;

/**
 *
 * @author nelson
 */
public class StopwatchBtn extends JButton {
    
    private static boolean count = false;
    private static boolean reset = false;
    private Timer timer;
    private Chronometer chronometer;
    private Calendar calendar;
    
    public StopwatchBtn() {
        this.setIcon(new ImageIcon((getClass().getResource("chronometer.png"))));
        this.setText("00:00:00");
        this.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnTimeMouseClicked(evt);
            }
        });
    }

    public static boolean isCount() {
        return count;
    }

    public static boolean isReset() {
        return reset;
    }

    public static void setReset(boolean reset) {
        StopwatchBtn.reset = reset;
    }

    private void start() {
        count = true;

        chronometer = new Chronometer(this, calendar);
        this.timer = new Timer();
        this.timer.scheduleAtFixedRate(this.chronometer, 0, 1000);
    }

    private void pause() {
        count = false;
        this.calendar = chronometer.getCalendar();
    }

    private void reset() {
        this.setText("00:00:00");
        count = false;
        reset = true;
    }
    
    private void btnTimeMouseClicked(java.awt.event.MouseEvent evt) {                                     
    if (evt.getButton() == java.awt.event.MouseEvent.BUTTON1) {

        //for all actions, cancel the last timer and initialize other.
        if (timer != null) {
            this.timer.cancel();
        }

        if (evt.getClickCount() >= 2) {
            reset();
        } else if (evt.getClickCount() == 1) {
            if (!isCount()) {
                start();
            } else {
                pause();
            }
        }
        
        this.validate();
        this.repaint();
    }
}  

}
